package com.hulk.sequence;

import com.hulk.sequence.annotation.EnableSnowFlakeSeqConfig;
import com.hulk.sequence.builder.SnowflakeSeqBuilder;
import com.hulk.sequence.properties.SequenceSnowflakeProperties;
import com.hulk.sequence.worker.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author hulk
 * @date 2019-05-26
 */


@Configuration
@ConditionalOnMissingBean(Sequence.class)
@ConditionalOnBean(annotation = EnableSnowFlakeSeqConfig.class)
@EnableConfigurationProperties(SequenceSnowflakeProperties.class)
public class SnowFlakeSeqAutoConfiguration {

	@Autowired
	private SequenceSnowflakeProperties properties;

	/**
	 * snowflake 算法作为发号器实现
	 *
	 * @param properties
	 * @return
	 */
	@Bean
	@ConditionalOnProperty("xsequence.snowflake")
	public Sequence snowflakeSequence() {
		return SnowflakeSeqBuilder
				.create()
				.datacenterId(properties.getDatacenterId())
				.workerId(properties.getWorkerId())
				.build();
	}
}